<template>
  <div>
  </div>
</template>

<script>
import { accessToken, userInfo, userLogin } from '@/api/api'
import cache from '@/utils/cache'
export default {
  data() {
    return {
      code: '',
      loading: null
    }
  },
  mounted() {
    /**
     * 1、从URL上获取code
     * 2、通过code获取access_token
     * 3、通过access_token获取用户信息
     * 4、通过userId和username登录，登录成功后跳转
     */
    const code = this.getUrlParams('code')
    // console.log('--code', code);
    this.code = code
    this.getAccessToken(code)
  },
  methods: {
    //从URL获取code
    getUrlParams(name) {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      let param = window.location.search.substr(1).match(reg);
      return param && param[2];
    },
    //获取access_token
    async getAccessToken(token) {
      this.loading = this.$loading({
        lock: true,
        text: '获取登录参数中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.3)'
      })
      try {
        const res = await accessToken(token)
        const data = JSON.parse(res.data)
        // console.log('token', res.data);
        if (data && data.access_token) {
          this.getUserInfo(data.access_token)
        }
        this.loading && this.loading.close()
      } catch (error) {
        console.log(error);
      }
    },
    // 获取用户信息
    async getUserInfo(token) {
      this.loading = this.$loading({
        lock: true,
        text: '获取用户信息...',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.3)'
      })
      try {
        const res = await userInfo(token)
        // console.log('--res', res);
        // console.log('--info', userInfo);
        if (res && res.code == 200) {
          const userInfo = { ...res.userInfo }
          this.login(userInfo.userId, userInfo.username)
        }
        this.loading && this.loading.close()
      } catch (error) {
        console.log(error);
      }
    },
    //登录
    async login(userId, username) {
      // console.log('--login--', userId, username);
      this.loading = this.$loading({
        lock: true,
        text: '登录中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.3)'
      })
      try {
        const data = {
          userId,
          username,
        }
        const res = await userLogin(data)
        this.loading && this.loading.close()
        if (res) {
          // console.log('--login', res);
          cache.local.setJSON('userInfo', res.data)
          this.$message.success('登录成功')
          setTimeout(() => {
            this.$router.push('/home')
          }, 1000)
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>